package com.flight.trans.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.adapter.StoreroomInventoryDetailsAdapter;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.bean.StorageAreaBean.StorageAreaData;
import com.flight.trans.bean.StoreroomInventoryBean.StoreroomInventoryData;
import com.flight.trans.bean.StoreroomInventoryDetailBean.StoreroomInventoryDetailData;
import com.flight.trans.bean.UnusualBean;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.StorageAreaDialog;
import com.flight.trans.view.edit.EditorActivity;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 盘库详情
 */
public class StoreroomInventoryDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private TextView mTvOrderCount ,//运单数
            mTvMoreOrderCount ,//多收
            mTvLessOrderCount ,//少收
            mTvUnusualOrderCount ,//异常数
            mTvInventoryPerson ,//盘库人
            mTvInventoryTime ;//盘库时间
    private LinearLayout mLlInventoryContainer ,// 盘库人
            mLlOperationInfo;//操作
    private TextView mTvTitleName,//标题
            mTvStorageArea,//存放区域
            mTvOperationInfo;//操作
    private Button mBtnBlankRecord ,//空白记录
            mBtnIssue ;//提交

    private TwinklingRefreshLayout mRefreshLayout ;
    private RecyclerView mRvContainer ;

    private StoreroomInventoryDetailsAdapter inventoryDetailsAdapter;

    private TextView mTvDeep ;// 目的地
    private boolean isConfirm = true;

    // 存放区域筛选
    private List<StorageAreaData> mStorageAreaList;

    private List<StoreroomInventoryDetailData> mInventoryDetailList ,mSearchDataList;

    private StoreroomInventoryData mInventoryData ;
    private int turnType ;
    private int moreOrderCnt ,lessOrderCnt , unusualOrderCount ;

    @Override
    protected int setContentView() {
        return R.layout.activity_storeroom_inventory_details;
    }

    @Override
    protected void initView() {
        mLlContainer = findViewById(R.id.mLlContainer);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mTvStorageArea = findViewById(R.id.mTvStorageArea);
        mBtnBlankRecord = findViewById(R.id.mBtnBlankRecord);
        mBtnIssue = findViewById(R.id.mBtnIssue);
        mRefreshLayout = findViewById(R.id.mRefreshLayout);
        mRvContainer = findViewById(R.id.mRvContainer);
        mTvOperationInfo = findViewById(R.id.mTvOperationInfo);

        mTvDeep = findViewById(R.id.mTvDeep);

        mTvOrderCount = findViewById(R.id.mTvOrderCount);
        mTvMoreOrderCount = findViewById(R.id.mTvMoreOrderCount);
        mTvLessOrderCount = findViewById(R.id.mTvLessOrderCount);
        mTvUnusualOrderCount = findViewById(R.id.mTvUnusualOrderCount);
        mTvInventoryPerson = findViewById(R.id.mTvInventoryPerson);
        mTvInventoryTime = findViewById(R.id.mTvInventoryTime);

        mLlInventoryContainer = findViewById(R.id.mLlInventoryContainer);
        mLlOperationInfo = findViewById(R.id.mLlOperationInfo);
    }

    @Override
    protected void initData() {
        turnType = mBundle.getInt(Constant.TurnType);
        mInventoryData = (StoreroomInventoryData) mBundle.getSerializable(Constant.INFO);
        IsEditor = mBundle.getBoolean(Constant.IsEditor);

        ConstantInfo.UnusualIDList.clear();

        mTvTitleName.setText(getString(turnType == 0 ? R.string.title_enter_port_inventory : R.string.title_leave_port_inventory));

        // 初始化信息
        if(mInventoryData == null){
            mLlInventoryContainer.setVisibility(View.GONE);
        } else {
            mLlInventoryContainer.setVisibility(View.VISIBLE);
            mTvInventoryPerson.setText(mInventoryData.getUserName());//盘库人
            if(!TextUtils.isEmpty(mInventoryData.getCreateTime()))
                mTvInventoryTime.setText(mInventoryData.getCreateTime().split(" ")[1]);//盘库时间
        }

        CommonUtils.setScreenContainerPaddingTop(mLlContainer);
        CommonUtils.onFinishTouch(mActivity , mLlContainer);

        mTvDeep.setText(getString(turnType == 0 ? R.string.text_starting_station : R.string.text_deap));
        mTvOperationInfo.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnBlankRecord.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mLlOperationInfo.setVisibility(IsEditor ? View.VISIBLE : View.GONE);

        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadmore(false);
    }

    @Override
    protected void initConnect() {
        linked(true);
    }

    private void linked(boolean isFirst){
        NetworkUtils.getStoreroomInventoryDetail(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                if(isFirst){
                    mInventoryDetailList = (List<StoreroomInventoryDetailData>) body;

                    if(mInventoryDetailList == null)
                        mInventoryDetailList = new ArrayList<>();
                }else {
                    List<StoreroomInventoryDetailData> mDataList = (List<StoreroomInventoryDetailData>) body;
                    Map<String , StoreroomInventoryDetailData> mDataMap = new HashMap<>();

                    for (int i = 0; i < mDataList.size(); i++) {
                        mDataMap.put(mDataList.get(i).getOrderNo() , mDataList.get(i));
                    }

                    for (int i = 0; i < mInventoryDetailList.size(); i++) {
                        mInventoryDetailList.get(i).setAnomalyCnt(mDataMap.get(mInventoryDetailList.get(i).getOrderNo()).getAnomalyCnt());
                    }
                }

                initSelectionAreaData();

                initLocationData();
                initAdapter();
            }
        }, mInventoryData == null ? -1 : mInventoryData.getId() , turnType == 0);
    }

    /**
     * 初始化本地数据
     */
    private void initLocationData() {
        if(mInventoryDetailList == null)
            return;

        moreOrderCnt = 0 ;
        lessOrderCnt = 0 ;
        unusualOrderCount = 0 ;

        for (int i = 0; i < mInventoryDetailList.size(); i++) {
            StoreroomInventoryDetailData detailData = mInventoryDetailList.get(i);

            if(detailData.getCheckNumber() > detailData.getNumber())
                moreOrderCnt ++ ;

            if(detailData.getCheckNumber() < detailData.getNumber() && detailData.getCheckNumber() != 0)
                lessOrderCnt ++ ;

            if(detailData.getAnomalyCnt() != 0)
                unusualOrderCount ++ ;
        }

        mTvUnusualOrderCount.setText(String.valueOf(unusualOrderCount));
        mTvOrderCount.setText(String.valueOf(mInventoryDetailList.size()));
        mTvMoreOrderCount.setText(String.valueOf(moreOrderCnt));
        mTvLessOrderCount.setText(String.valueOf(lessOrderCnt));
    }

    private void initAdapter(){
        initLocationData();

        inventoryDetailsAdapter = new StoreroomInventoryDetailsAdapter(mActivity, mSearchDataList, IsEditor , turnType , isConfirm);
        mRvContainer.setAdapter(inventoryDetailsAdapter);
        mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

        inventoryDetailsAdapter.setOnTextClickListener(onClickTextListener);
        inventoryDetailsAdapter.setOnItemClickListener(onItemClickListener);
    }

    /**
     * 长按事件
     */
    private OnItemClickListener onItemClickListener = new OnItemClickListener(){
        @Override
        public void onLongClick(View view, int position) {
            if(mSearchDataList.get(position).getCheckSign() != 1){
                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_delete_blank)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteBlank(position);
                            }
                        }).show();
            }else {
                ToastUtils.showToast(R.string.toast_item_selected);
            }
        }
    };

    /**
     * 确认删除
     * @param position
     */
    private void deleteBlank(int position) {
        int pos = -1 ;
        for (int i = 0; i < mInventoryDetailList.size(); i++) {
            if(mInventoryDetailList.get(i).getOrderNo().equals(mSearchDataList.get(position).getOrderNo()))
                pos = i;
        }

        mInventoryDetailList.remove(pos);

        initSelectionAreaData();
    }

    /**
     * 点击
     */
    private OnTextClickListener onClickTextListener = new OnTextClickListener() {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvOrderNo:
                    // 运单号
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mSearchDataList.get(position).setOrderNo(content);

                            mInventoryDetailList.set(mSearchDataList.get(position).getPosition() , mSearchDataList.get(position));
                            initAdapter();
                        }
                    } , mSearchDataList.get(position).getOrderNo() , false);
                    break;
                case R.id.mTvProductName:
                    // 品名
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mSearchDataList.get(position).setTradeName(content);

                            mInventoryDetailList.set(mSearchDataList.get(position).getPosition() , mSearchDataList.get(position));
                            initAdapter();
                        }
                    } , mSearchDataList.get(position).getTradeName() , false);
                    break;
                case R.id.mTvStorageArea:
                    // 区域选择
                    StorageAreaDialog.getInstance(mActivity , turnType == 0 ? Constant.EnterPortStorage : Constant.LeavePortStorage)
                            .setSingleSelect(true)
                            .setConfirmButton(new StorageAreaDialog.OnStorageOnClickListener() {
                                @Override
                                public void onClick(List<StorageAreaData> storageAreaList) {
                                    mSearchDataList.get(position).setWarehouseAreaNames(storageAreaList.get(0).getName());
                                    mSearchDataList.get(position).setWarehouseAreaIds(String.valueOf(storageAreaList.get(0).getId()));

                                    mInventoryDetailList.set(mSearchDataList.get(position).getPosition() , mSearchDataList.get(position));
                                    initAdapter();
                                }
                            }).show();
                    break;
                case R.id.mTvRealCount:
                    // 运单件数
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mSearchDataList.get(position).setNumber(TextUtils.isEmpty(content) ? 0 : Integer.parseInt(content));

                            mInventoryDetailList.set(mSearchDataList.get(position).getPosition() , mSearchDataList.get(position));
                            initAdapter();
                        }
                    } , String.valueOf(mSearchDataList.get(position).getNumber()));
                    break;
                case R.id.mTvInventoryCount:
                    // 实到件数
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mSearchDataList.get(position).setCheckNumber(TextUtils.isEmpty(content) ? 0 : Integer.parseInt(content));

                            mInventoryDetailList.set(mSearchDataList.get(position).getPosition() , mSearchDataList.get(position));
                            initAdapter();
                        }
                    } , String.valueOf(mSearchDataList.get(position).getCheckNumber()));
                    break;
                case R.id.mTvInventoryStatus:
                    // 异常状态
                    mIntent = new Intent(mActivity , UnusualListActivity.class);
                    mBundle = new Bundle();
                    mBundle.putBoolean(Constant.IsEditor , IsEditor);
                    mBundle.putInt(Constant.Position , position);
                    if(mSearchDataList.get(position).isBlankRecord()){
                        mBundle.putInt(Constant.TurnType , 1);
                        UnusualBean unusualBean = new UnusualBean();
                        unusualBean.setData(mSearchDataList.get(position).getAnomalyRecordVOList());
                        mBundle.putSerializable(Constant.INFO , unusualBean);
                    }else {
                        mBundle.putInt(Constant.Business_ID , turnType == 0 ? mSearchDataList.get(position).getInwardOrderId() : mSearchDataList.get(position).getOutwardOrderId());
                    }
                    mBundle.putInt(Constant.Source_Type , turnType == 0 ? 3 : 4);
                    mBundle.putString(Constant.Key_Order_No , mSearchDataList.get(position).getOrderNo());
                    mIntent.putExtras(mBundle);
                    turnActForResult(mIntent);
                    break;
                case R.id.mBtnOperation:
                    // 操作
                    if(isConfirm) {
                        StoreroomInventoryDetailData detailBean = mSearchDataList.remove(position);
                        detailBean.setCheckSign(detailBean.getCheckSign() == 0 ? 1 : 0);

                        if (detailBean.getCheckSign() == 1) {
                            mSearchDataList.add(detailBean);
                        } else {
                            mSearchDataList.add(0, detailBean);
                        }

                        initAdapter();
                    } else {
                        AlertDialog.getInstance(mActivity)
                                .setContent("是否确认将运单 " + mSearchDataList.get(position).getOrderNo() + "置为出库？")
                                .setConfirmButton(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        NetworkUtils.updateOrderToOut(new OkGoBackListener(mActivity) {
                                            @Override
                                            public void onSuccess(Object body) {
                                                mSearchDataList.remove(position);
                                                initAdapter();
                                            }
                                        }, turnType == 0 ? mSearchDataList.get(position).getInwardOrderId() : mSearchDataList.get(position).getOutwardOrderId(), turnType);
                                    }
                                }).show();
                    }
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mIbBack:
                // 返回
                onBackPressed();
                break;
            case R.id.mTvStorageArea:
                // 存放区域
                StorageAreaDialog.getInstance(mActivity , turnType == 0 ? Constant.EnterPortStorage : Constant.LeavePortStorage)
                        .setSelectedArea(mStorageAreaList)
                        .setConfirmButton(new StorageAreaDialog.OnStorageOnClickListener() {
                            @Override
                            public void onClick(List<StorageAreaData> storageAreaList) {
                                mStorageAreaList = storageAreaList;

                                initSelectionAreaData();
                            }
                        })
                        .show();
                break;
            case R.id.mBtnBlankRecord:
                // 空白记录
                if(mInventoryDetailList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                StoreroomInventoryDetailData inventoryBean = new StoreroomInventoryDetailData();
                inventoryBean.setOrderNo(CommonUtils.getTimeStamp());
                inventoryBean.setBlankRecord(true);
                mInventoryDetailList.add(0 , inventoryBean);
                initSelectionAreaData();
                break;
            case R.id.mBtnIssue:
                // 出库、盘库
                isConfirm = !isConfirm ;

                mBtnIssue.setText(getString(isConfirm ? R.string.button_issue : R.string.text_inventory));
                inventoryDetailsAdapter.setConfirm(isConfirm);
                break;
            case R.id.mBtnSubmit:
                // 提交
                if(mInventoryDetailList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                if(IsSaveIng){
                    ToastUtils.showToast(R.string.toast_save_ing);
                    return;
                }
                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_submit_storeroom_info)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clickSubmit();
                            }
                        }).show();
                break;
        }
    }

    /**
     * 初始化选择区域
     */
    private void initSelectionAreaData() {
        if(mStorageAreaList != null && mStorageAreaList.size() != 0){
            mTvStorageArea.setText("已选 " + mStorageAreaList.size() + " 区域");

            List<Integer> idList ;
            mSearchDataList = new ArrayList<>();
            for (int i = 0; i < mInventoryDetailList.size(); i++) {
                if(TextUtils.isEmpty(mInventoryDetailList.get(i).getWarehouseAreaIds()))
                    continue;

                idList = new ArrayList<>();
                String[] ids = mInventoryDetailList.get(i).getWarehouseAreaIds().split(",");
                for (int k = 0; k < ids.length; k++) {
                    idList.add(Integer.parseInt(ids[k])) ;
                }

                for (int j = 0; j < mStorageAreaList.size(); j++) {
                    if(idList.contains(mStorageAreaList.get(j).getId()))
                        mSearchDataList.add(mInventoryDetailList.get(i));
                }
            }
        } else {
            mTvStorageArea.setText("");
            mSearchDataList = mInventoryDetailList ;
        }

        initAdapter();
    }

    /**
     * 确认提交
     */
    private void clickSubmit() {
        IsSaveIng = true ;
        NetworkUtils.saveStoreroomInventoryData(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                CommonUtils.writeCrashLog("盘库数据保存成功");
                IsSaveIng = false;
                ToastUtils.showToast(R.string.toast_submit_success);
                onFinish(Constant.RESULT_CODE);
            }

            @Override
            public void onError() {
                IsSaveIng = false;
                CommonUtils.writeCrashLog("盘库数据保存失败");
            }
        }, JsonUtils.parseBeanToJson(mInventoryDetailList) , turnType == 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_CODE){
            mBundle = data.getExtras();
            mSearchDataList.get(mBundle.getInt(Constant.Position)).setAnomalyRecordVOList(((UnusualBean)mBundle.getSerializable(Constant.INFO)).getData());
            mInventoryDetailList.get(mSearchDataList.get(mBundle.getInt(Constant.Position)).getPosition()).setAnomalyRecordVOList(((UnusualBean)mBundle.getSerializable(Constant.INFO)).getData());
            mInventoryDetailList.get(mSearchDataList.get(mBundle.getInt(Constant.Position)).getPosition()).setAnomalyCnt(((UnusualBean)mBundle.getSerializable(Constant.INFO)).getData().size());
            initAdapter();
        }else if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_REFRESH_CODE){
            linked(false);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        if(mInventoryData == null)
            return;

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , turnType == 0 ? ConstantInfo.IN_STORAGE_CHECK : ConstantInfo.OUT_STORAGE_CHECK , mInventoryData.getId());
    }
}
